package search.graph;

import java.util.Collection;
import java.util.LinkedList;

public class BellmanFord {
	
	
	public static void relaxGraph(Node start, Graph graph) {
		
		LinkedList<Edge> allEdges = start.getAllEdges();
		graph.findNode(start.toString()).setBFdistance(0.0);		
		
		Boolean geaendert = true;
//		System.out.println(graph.nodes().size() + " " + allEdges.size());
		for (int i = 0; i < graph.nodes().size()-1; i++) {
			
			if (!geaendert) { 
				System.out.println("stopped after "+ i);
				break;
			}
			geaendert = false;
			for (Edge edge : start.getAllEdges()) {
				Node n1 = edge.getNode(0);
				Node n2 = edge.getNode(1);
				if (n1.getBFdistance() + edge.getEdgeLength() < n2.getBFdistance()) {
					n2.setBFdistance(n1.getBFdistance() + edge.getEdgeLength());
					n2.setNewVorgaenger(n1);
					geaendert = true;
				}
				
				if (n2.getBFdistance() + edge.getEdgeLength() < n1.getBFdistance()) {
					n1.setBFdistance(n2.getBFdistance() + edge.getEdgeLength());
					n1.setNewVorgaenger(n2);
					geaendert = true;
				}
			}
			
		}
	}
	
	
	public static void initializeBF(Collection<Node> nodes) {
		for (Node node : nodes) {
			node.initializeForBF();
		}
	}

	//nicht verwenden, wirft fehler beim aufbau des pfades
	public static Path getBFPath(Node goal, Node start) {
		
		
//		Path path = new Path(start, goal);
//		LinkedList<Node> nodes = new LinkedList<Node>();
//		Node pos = goal;
//		
//		while (pos != start) {
//			nodes.addFirst(pos);
//			pos = pos.getVorgaenger();
//		}
//		
//		for (int i = 0; i < nodes.size(); i++) {
//			path.addWithBF(nodes.get(i));
//		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		LinkedList<Node> reversePath = new LinkedList<Node>();
		Node pos = goal;
		System.out.println(goal + " " + start);
		Path path = new Path(start, goal);
		while(pos != start) {
			
//			for( Node nn  : pos.directedNeighbours() ) {
//				System.out.print(nn + " ");
//			}
			System.out.println("V: " + pos.getBFdistance());
			
			reversePath.addFirst(pos);
			pos = pos.getVorgaenger();
			 
			
		}
		
		
		for (int i = 0; i < reversePath.size(); i++) {
			System.out.println(path.getLastNode());
			System.out.println(reversePath);
			
			path = path.addWithBF(reversePath.get(i));
			path.mark();
		}
		System.out.println(path.getLastNode());
		return path;
	}
	
}
